// scaup - Scala up!
// (c) 2008-2010, Normen Müller, normen.mueller@gmail.com  
// $Id: strings.scala 78 2010-05-13 12:25:41Z normen.mueller $
package scaup.data

import java.io.File
import java.net.{URI, URL}
import java.security.MessageDigest

/** Adds extra methods to <code>java.lang.String</code>.
 * 
 *  @author <a href="mailto:normen.mueller@googlemail.com">Normen M&#xFC;ller</a>
 *  @version 0.0.4
 * 
 *  @param string to enclose/ extend
 */
private [scaup] class StringExtras(string: String) { 
  if (string == null)
    error("String may not be null")
  
  /** Constructs a new <code>File</code> instance by parsing the enclosed string <code>string</code>.
   *  If <code>string</code> is the empty string, then the result is the empty abstract pathname.
   */
  lazy val toFile = new File(string)
  
  /** Constructs a new <code>URL</code> instance by parsing the enclosed string <code>string</code>.
   *  The exact form of the URL is system-dependent.
   * 
   *  @see <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/URL.html#URI(java.lang.String)">
   *    java.net.URL#URL(java.lang.String)</a></code>.
   */
  lazy val toURL = new URL(string)
  
  /** Constructs a new <code>URI</code> by parsing the enclosed string <code>string</code>.
   * 
   *  @see <code><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/URI.html#URI(java.lang.String)">
   *    java.net.URI#URI(java.lang.String)</a></code>.
   */
  lazy val toURI = new URI(string)
  
  lazy val toMD5: String = ((md: MessageDigest) =>
    try { 
      md.update(string.getBytes)
      md.digest mkString
    } catch { case ex@_ => error(ex.getMessage) }
  )(MessageDigest.getInstance("MD5"))
  
  def regex(flags: Int) = new scaup.util.matching.Regex(string, flags)
  
  def splitAt(index: Int): (String, String) =
    if (index < 0) ("", string)
    else if (index >= string.length) (string, "")
    else (string.substring(0,index), string.substring(index+1))
    
  /** Flush enclosed string <code>string</code> into file <code>f</code> in UTF-8 encoded format
   */
  def >>> (f: Option[File]): Option[File] = f match { case Some(v) => Some(this >>> v) case _ => None }
  
  /** Flush enclosed string <code>string</code> into file <code>f</code> in UTF-8 encoded format
   */
  def >>> (f: File): File = ((out: java.io.BufferedWriter) =>
    try { 
      out.write(string)
      out.close()
      f
    } catch { case ex@_ => error(ex.getMessage) }
  )(new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(f),"UTF8")))
  //)(new java.io.BufferedWriter(new java.io.FileWriter(f)))  
}
